package com.ruoyi.web.controller.workJob;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.worker.domain.*;
import com.ruoyi.worker.service.EmploymentPlanService;
import com.ruoyi.worker.service.WorkerInfoService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @ClassName: employmentPlanController
 * @Description:
 * @Author: 刘松山
 * @Date: 2021/9/12 10:27
 */
@RestController
@RequestMapping("/employment/plan")
public class EmploymentPlanController extends BaseController {
    private static final Logger LOGGER = LoggerFactory.getLogger(EmploymentPlanController.class);
    @Autowired
    private EmploymentPlanService employmentPlanService;
    @Autowired
    private WorkerInfoService workerInfoService;

    /**
     * 获取用工名单汇总记录列表
     *
     * @param employmentPlanStatistics
     * @return com.ruoyi.common.core.page.TableDataInfo
     * @author 刘松山
     * @date 2021/9/12 13:17
     */
   // @PreAuthorize("@ss.hasPermi('job:employmentPlan:detail')")
    @GetMapping("/listEmploymentPlanStatistics")
    public TableDataInfo listEmploymentPlanStatistics(EmploymentPlanStatistics employmentPlanStatistics) {
        startPage();
        List<EmploymentPlanStatistics> list = employmentPlanService.listEmploymentPlanStatistics(employmentPlanStatistics);
        return getDataTable(list);
    }

    /**
     * 获取用工名单详情列表
     *
     * @param employmentPlan
     * @return com.ruoyi.common.core.page.TableDataInfo
     * @author 刘松山
     * @date 2021/9/12 13:17
     */
   // @PreAuthorize("@ss.hasPermi('job:employmentPlan:detail:list')")
    @GetMapping("/listEmploymentPlan")
    public TableDataInfo listEmploymentPlan(EmploymentPlan employmentPlan) {
        startPage();
        List<EmploymentPlan> list = employmentPlanService.listEmploymentPlan(employmentPlan);
        return getDataTable(list);
    }
    /**
     * 获取年龄区间
     *
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author 刘松山
     * @date 2021/9/12 13:24
     */

   // @PreAuthorize("@ss.hasPermi('workJobApi:attendance:query')")
    @GetMapping(value = {"/getAgeRange"})
    public AjaxResult getAgeRange() {
        AjaxResult ajax = AjaxResult.success();
        AgeRange a = employmentPlanService.getAgeRange();
        ajax.put(AjaxResult.DATA_TAG, a);
        return ajax;
    }
    /**
     * 新增年龄区间
     *
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author 刘松山
     * @date 2021/9/12 13:24
     */
    //@PreAuthorize("@ss.hasPermi('workJobApi:attendance:add')")
    @Log(title = "新增", businessType = BusinessType.INSERT)
    @PostMapping(value = {"/addAgeRange"})
    public AjaxResult addAgeRange(@Validated @RequestBody AgeRange ageRange) {
        ageRange.setCreateBy(getUsername());
        if(ageRange.getStartAge()>=ageRange.getEndAge()){
            return AjaxResult.error("结束年龄不能小于等于开始年龄，请核对");
        }
        return toAjax(employmentPlanService.addAgeRange(ageRange));
    }

    /**
     * 修改年龄区间
     *
     * @param ageRange
     * @return com.ruoyi.common.core.domain.AjaxResult
     * @author 刘松山
     * @date 2021/9/12 13:24
     */
    //@PreAuthorize("@ss.hasPermi('job:employmentPlan:ageSet')")
    @Log(title = "修改", businessType = BusinessType.UPDATE)
    @PutMapping(value = {"/modifyAgeRange"})
    public AjaxResult modifyAgeRange(@Validated @RequestBody AgeRange ageRange) {
        ageRange.setUpdateBy(getUsername());
        return toAjax(employmentPlanService.modifyAgeRange(ageRange));
    }
   /**
    * 移出名单
    * @author 刘松山
    * @date 2021/9/15 15:31
    * @param ids
    * @return com.ruoyi.common.core.domain.AjaxResult
    */
    //@PreAuthorize("@ss.hasPermi('job:employmentPlan:detail:remove')")
    @Log(title = "删除", businessType = BusinessType.DELETE)
    @DeleteMapping("/delEmployment/{ids}")
    public AjaxResult delEmployment(@PathVariable Long[] ids) {
        return toAjax(employmentPlanService.delEmployment(ids));
    }
    //@PreAuthorize("@ss.hasPermi('job:employmentPlan:import')")
    @PostMapping("/addEmploymentPlan")
    public AjaxResult addEmploymentPlan(MultipartFile file) {
        List<EmploymentPlan> employmentPlans = null;
        try {
            employmentPlans = baseImport(file.getInputStream(), 1, 1, false, EmploymentPlan.class);
        } catch (Exception e) {
            LOGGER.error("班组信息导入失败:[{}]", e.getMessage(), e);
        }
        if (null == employmentPlans) {
            return AjaxResult.error("excel班组信息导入失败，信息为空");
        }
        EmploymentPlan e = employmentPlans.get(0);
        String workNeedCode = e.getOrderCode();
        e.setOrderCode(workNeedCode);
        for (int i = 0; i < employmentPlans.size(); i++) {
            if(!Objects.equals(employmentPlans.get(i).getOrderCode(),workNeedCode)){
                return AjaxResult.error("第" + (i + 3) + "行用工需求单号和第3行不同,请核对");
            }

            if (null == employmentPlans.get(i).getWorkerName()) {
                return AjaxResult.error("第" + (i + 3) + "行员工姓名为空,请核对");
            }
            if (null == employmentPlans.get(i).getIdCard()) {
                return AjaxResult.error("第" + (i + 3) + "行,"+employmentPlans.get(i).getWorkerName()+"身份证为空,请核对");
            }
            if (null == employmentPlans.get(i).getCompanyName()) {
                return AjaxResult.error("第" + (i + 3) + "行,"+employmentPlans.get(i).getWorkerName()+"渠道商为空,请核对");
            }
            if (DateUtils.extractYearMonthDayOfIdCard(employmentPlans.get(i).getIdCard()) == null) {
                return AjaxResult.error("第" + (i + 3) + "行,"+employmentPlans.get(i).getWorkerName()+"身份证格式不对,请核对");
            }
        }


//        List<List<EmploymentPlan>> listOfList = Lists.newArrayList();
//        employmentPlans.stream().collect(Collectors.groupingBy(EmploymentPlan::getIdCard, Collectors.toList()))
//                .forEach((idCard, list) -> {
//                    listOfList.add(list);
//                });
//        String errName = null;
//
//        for (List<EmploymentPlan> toolDomains : listOfList) {
//            if (toolDomains.size() > 1) {
//                errName = toolDomains.get(0).getWorkerName();
//                break;
//            }
//        }
//        if (StringUtils.isNotBlank(errName)) {
//            return AjaxResult.error(errName.concat("信息重复,请核对"));
//        }

        List<EmploymentPlan> lst = employmentPlans.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(
                        () -> new TreeSet<>(Comparator.comparing(o -> o.getWorkerName() + "_" + o.getIdCard() + "_" + o.getTimeShiftName()))),
                ArrayList::new));

        if(lst.size()<employmentPlans.size()){
            return AjaxResult.error("信息重复了"+(employmentPlans.size()-lst.size())+"条,请核对");
        }


        //获取年龄范围
        AgeRange ageRange = employmentPlanService.getAgeRange();
        //黑名单
        WorkerInfos workerInfos = new WorkerInfos();
        //workerInfos.setStatus(0);
        List<WorkerInfos> workerInfosList = workerInfoService.getWorkerInfos(workerInfos);
        List<WorkerInfos>  badWorkerInfosList = new ArrayList<>();
        List<WorkerInfos>  otherWorkerInfosList = new ArrayList<>();
        for(WorkerInfos w :workerInfosList){
            if(w.getStatus()==0){
                badWorkerInfosList.add(w);
            }else{
                otherWorkerInfosList.add(w);
            }
        }


        //校验年龄
        List<EmploymentPlan> tempList = new ArrayList<>();
        int  k =0;
        for (EmploymentPlan ep : employmentPlans) {
            k++;
            int flag = 0;
            //年月日
            String yyr = DateUtils.extractYearMonthDayOfIdCard(ep.getIdCard());

            int age = DateUtils.getAge(DateUtils.dateTime("yyyy-MM-dd", yyr));
            if (age != -1 && age >= ageRange.getStartAge() && age <= ageRange.getEndAge()) {
                for (WorkerInfos w : badWorkerInfosList) {
                    if (Objects.equals(w.getIdCard(), ep.getIdCard())) {
                        flag = 1;
                        break;
                    }
                }
            } else {
                flag = 1;
                return AjaxResult.error("第" + (k + 3) + "行,"+ep.getWorkerName()+"年龄不符合,请核对");
            }
            if (flag == 0) {
                tempList.add(ep);
            }else{
                return AjaxResult.error("第" + (k + 3) + "行,"+ep.getWorkerName()+"已经加入了黑名单,请核对");
            }


        }
        List<EmploymentPlan> resultList = new ArrayList<>();
        int companyNum =0;
        if (tempList.size() > 0) {
            k=0;
            //获取渠道商报名的
            List<EmploymentPlan> companyList = employmentPlanService.ListAttendanceCompany(e);
            companyNum=companyList.size();
            for (EmploymentPlan ep : tempList) {
                k++;
                String idCard = ep.getIdCard();
                int flag = 0;
                for (EmploymentPlan companyep : companyList) {
                    if (Objects.equals(companyep.getIdCard(), ep.getIdCard())) {
                        flag = 1;
                        break;
                    }
                }
                if (flag == 0) {
                    resultList.add(ep);
                }else{
                    return AjaxResult.error("第" + (k + 3) + "行,"+ep.getWorkerName()+"已经在小程序报名过了,请核对");
                }
            }
        }
        if (resultList.size() > 0) {
            //录入
            //查询是否导入过了
            EmploymentPlan hadEmploymentPlan = employmentPlanService.countAttendanceCompany(e);
            if (null != hadEmploymentPlan) {
                employmentPlanService.delAllAttendanceCompany(e);
            }
            employmentPlanService.delAllEmploymentPlanStatistics(e);
            employmentPlanService.importEmploymentPlan(resultList);

            OperationNeedPojo op = new OperationNeedPojo();
            op.setNeedTime(DateUtils.parseDateToStr("yyyy-MM-dd",e.getWorkTime()));
            op.setTaskNumber(e.getOrderCode());
            OperationNeedPojo opBack = employmentPlanService.getworkNeedInfo(op);
              if(null==opBack){
                  return AjaxResult.error("用工需求单和用工日期对应的记录不存在,请核对");
              }
            EmploymentPlanStatistics employmentPlanStatistics =new EmploymentPlanStatistics();
            employmentPlanStatistics.setTotalNum(opBack.getSumNumber());
            //导入的加上小程序里的
            employmentPlanStatistics.setSignupNum(resultList.size()+companyNum);
            employmentPlanStatistics.setWorkTime(e.getWorkTime());
            employmentPlanStatistics.setOrderCode(e.getOrderCode());
            employmentPlanService.addAttendanceStatistics(employmentPlanStatistics);

            //如果导入的临时工 不在临时工信息表里 保存
            workerInfosList.clear();
             for(EmploymentPlan  ep:resultList){
                 String idCard=ep.getIdCard();
                 int flag =0 ;
                 for(WorkerInfos w:otherWorkerInfosList){
                     if(Objects.equals(idCard,w.getIdCard())){
                         flag =1;
                         break;
                     }
                 }
                 if(flag==0){
                     WorkerInfos addWorkerInfos  = new WorkerInfos();
                     addWorkerInfos.setStatus(1);
                     addWorkerInfos.setIdCard(idCard);
                     addWorkerInfos.setWorkerName(ep.getWorkerName());
                     addWorkerInfos.setSex(ep.getSex());
                     addWorkerInfos.setCreateBy(getUsername());
                     addWorkerInfos.setPhoneCode(ep.getPhoneCode());
                     //年月日
                     String yyr = DateUtils.extractYearMonthDayOfIdCard(ep.getIdCard());

                     int age = DateUtils.getAge(DateUtils.dateTime("yyyy-MM-dd", yyr));
                     addWorkerInfos.setAge(age);
                     workerInfosList.add(addWorkerInfos);
                 }
             }
           if(workerInfosList.size()>0){
               workerInfoService.addBatchWorkerInfo(workerInfosList);
           }

        }else{
            return AjaxResult.error("本次导入数据经过去重、去黑名单、校验年龄后已无导入数据了");
        }


        return AjaxResult.success();
    }

    private <T> List<T> baseImport(InputStream inputStream, Integer titleRows, Integer headerRows,
                                   boolean needVerify, Class<T> pojoClass) throws Exception {
        if (inputStream == null) {
            return null;
        } else {
            final ImportParams params = new ImportParams();
            params.setTitleRows(titleRows);
            params.setHeadRows(headerRows);
            params.setNeedVerify(true);
            params.setNeedSave(false);
            return ExcelImportUtil.importExcel(inputStream, pojoClass, params);
        }

    }

}
